package notes

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"tao-admin/internal/model"
)

type NoteService struct {
	NoteManager *NoteManager
}

func NewNoteService() *NoteService {
	return &NoteService{
		NoteManager: &NoteManager{},
	}
}

func (s NoteService) CreateNoteItem(ctx *gin.Context) (err error, msg string) {
	var item model.NoteTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！(Unmarshal)"
	}

	if item.Title == nil || item.Body == nil ||
		item.CategoryId == nil || item.UserId == nil {
		return nil, "存在必填项未填写！"
	}
	err = s.NoteManager.CreateNoteMng(ctx, item)
	if err != nil {
		return err, "插入数据出错！"
	}
	return nil, ""
}

func (s NoteService) UpdateNoteItem(ctx *gin.Context) (interface{}, interface{}) {
	var item model.NoteTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！(Unmarshal)"
	}
	if item.Id == nil {
		return nil, "Id必传！"
	}
	err = s.NoteManager.UpdateNoteMng(ctx, item)
	if err != nil {
		return err, "更新数据出错！"
	}
	return nil, ""
}

func (s NoteService) DeletePlanItem(ctx *gin.Context) (interface{}, interface{}) {
	var item model.NoteTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！"
	}
	if item.Id == nil {
		return nil, "Id必传！"
	}
	err = s.NoteManager.DeleteNoteMng(ctx, item)
	if err != nil {
		return err, "删除数据出错！"
	}
	return nil, ""
}

func (s NoteService) GetNoteInfos(ctx *gin.Context) (interface{}, interface{}, interface{}) {
	condition := &SearchNoteCondition{}
	if title, isExist := ctx.GetQuery("title"); isExist == true {
		condition.Title = &title
	}
	if body, isExist := ctx.GetQuery("body"); isExist == true {
		condition.Body = &body
	}

	list, total, err := s.NoteManager.SearchNoteByCondition(ctx, condition)
	if err != nil {
		return nil, 0, err
	}
	log.Printf("SearchByConditionMng, list: %v, total: %v", &list, total)
	return list, total, nil
}
